import { Controller, Get, Query, Inject, Post, Files } from '@midwayjs/core';
import { TranslateService } from '../service/translate.service';

/**
 * 翻译控制器
 * 提供词汇翻译的API接口
 */
@Controller('/api')
export class TranslateController {
  @Inject()
  translateService: TranslateService;

  /**
   * 翻译单个词汇
   * GET /api/translate?word=xxx
   * @param word 要翻译的单词
   * @returns 翻译结果
   */
  @Get('/translate')
  async translateWord(@Query('word') word: string) {
    // 参数验证
    if (!word || !word.trim()) {
      return {
        success: false,
        message: '请提供要翻译的单词',
        data: null,
      };
    }

    try {
      const translation = await this.translateService.translateWord(word.trim());

      return {
        success: true,
        message: '翻译成功',
        data: {
          word: word.trim(),
          translation: translation,
          timestamp: new Date().toISOString()
        }
      };
    } catch (error) {
      console.error('翻译接口错误:', error);

      return {
        success: false,
        message: '翻译失败，请稍后重试',
        data: null,
        error: error.message
      };
    }
  }

  /**
   * 翻译句子
   * GET /api/translate/sentence?text=xxx
   * @param text 要翻译的句子
   * @returns 翻译结果
   */
  @Get('/translate/sentence')
  async translateSentence(@Query('text') text: string) {
    // 参数验证
    if (!text || !text.trim()) {
      return {
        success: false,
        message: '请提供要翻译的句子',
        data: null
      };
    }

    try {
      const translation = await this.translateService.translateSentence(text.trim());

      return {
        success: true,
        message: '句子翻译成功',
        data: {
          text: text.trim(),
          translation: translation,
          timestamp: new Date().toISOString()
        }
      };
    } catch (error) {
      console.error('句子翻译接口错误:', error);

      return {
        success: false,
        message: '句子翻译失败，请稍后重试',
        data: null,
        error: error.message
      };
    }
  }

  /**
   * 批量翻译多个词汇
   * GET /api/translate/batch?words=word1,word2,word3
   * @param words 逗号分隔的单词列表
   * @returns 批量翻译结果
   */
  @Get('/translate/batch')
  async translateWords(@Query('words') words: string) {
    // 参数验证
    if (!words || !words.trim()) {
      return {
        success: false,
        message: '请提供要翻译的单词列表',
        data: null
      };
    }

    try {
      const wordList = words.split(',').map(w => w.trim()).filter(w => w.length > 0);

      if (wordList.length === 0) {
        return {
          success: false,
          message: '单词列表不能为空',
          data: null
        };
      }

      // 限制批量翻译的数量
      if (wordList.length > 60) {
        return {
          success: false,
          message: '批量翻译最多支持60个单词',
          data: null
        };
      }

      const translations = await this.translateService.translateWords(wordList);

      return {
        success: true,
        message: '批量翻译完成',
        data: {
          total: wordList.length,
          results: translations,
          timestamp: new Date().toISOString()
        }
      };
    } catch (error) {
      console.error('批量翻译接口错误:', error);

      return {
        success: false,
        message: '批量翻译失败，请稍后重试',
        data: null,
        error: error.message
      };
    }
  }

  /**
   * 健康检查接口
   * GET /api/health
   * @returns 服务状态
   */
  @Get('/health')
  async health() {
    return {
      success: true,
      message: '翻译服务运行正常',
      data: {
        service: 'translate-service',
        status: 'healthy',
        timestamp: new Date().toISOString()
      }
    };
  }

  /**
   * 解析句子中的词组
   * GET /api/translate/phrases?text=xxx
   * @param text 要解析的句子
   * @returns 词组解析结果
   */
  @Get('/translate/phrases')
  async analyzePhrases(@Query('text') text: string) {
    // 参数验证
    if (!text || !text.trim()) {
      return {
        success: false,
        message: '请提供要解析的句子',
        data: null
      };
    }

    try {
      const analysis = await this.translateService.analyzePhrases(text.trim());

      return {
        success: true,
        message: '词组解析成功',
        data: {
          text: text.trim(),
          analysis: analysis,
          timestamp: new Date().toISOString()
        }
      };
    } catch (error) {
      console.error('词组解析接口错误:', error);

      return {
        success: false,
        message: '词组解析失败，请稍后重试',
        data: null,
        error: error.message
      };
    }
  }

  /**
   * 获取文本标题
   * GET /api/gettitle?content=xxx
   * @param content 要总结的内容
   * @returns 10个字的标题
   */
  @Get('/gettitle')
  async getTitle(@Query('content') content: string) {
    // 参数验证
    if (!content || !content.trim()) {
      return {
        success: false,
        message: '请提供要总结的内容',
        data: null
      };
    }

    try {
      const title = await this.translateService.getTitle(content.trim());

      return {
        success: true,
        message: '标题生成成功',
        data: {
          content: content.trim(),
          title: title,
          timestamp: new Date().toISOString()
        }
      };
    } catch (error) {
      console.error('标题生成接口错误:', error);

      return {
        success: false,
        message: '标题生成失败，请稍后重试',
        data: null,
        error: error.message
      };
    }
  }

  /**
   * 图片OCR文字识别
   * POST /api/translate/ocr
   * @param files 上传的图片文件
   * @returns OCR识别结果
   */
  @Post('/translate/ocr')
  async ocrImages(@Files() files: any[]) {
    console.log("🚀 ~ TranslateController ~ ocrImages ~ files:", files);
    console.log("🚀 ~ TranslateController ~ ocrImages ~ files type:", typeof files);
    console.log("🚀 ~ TranslateController ~ ocrImages ~ files length:", files ? files.length : 'undefined');

    // 参数验证
    if (!files || files.length === 0) {
      return {
        success: false,
        message: '请上传至少一张图片',
        data: null,
        debug: {
          files: files,
          filesType: typeof files,
          filesLength: files ? files.length : 'undefined'
        }
      };
    }

    // 限制上传文件数量
    if (files.length > 10) {
      return {
        success: false,
        message: '最多支持上传10张图片',
        data: null
      };
    }

    try {
      const ocrResults = await this.translateService.processOcrImages(files);

      return {
        success: true,
        message: 'OCR识别成功',
        data: {
          totalFiles: files.length,
          results: ocrResults,
          timestamp: new Date().toISOString()
        }
      };
    } catch (error) {
      console.error('OCR识别接口错误:', error);

      return {
        success: false,
        message: 'OCR识别失败，请稍后重试',
        data: null,
        error: error.message
      };
    }
  }
}
